<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\User;
use Admin\Form\UserForm;
use Zend\Db\Sql\Select;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\Iterator as paginatorIterator;
use Zend\Session\Container;

class UserController extends AbstractActionController {

    protected $userTable;

	public function kiemtra(){
		$module = "user";
		$controller = $this->params('controller');
		$action = $this->params('action');
		
		$sessionModule = new Container('module');
		$sessionController = new Container('controller');
		$sessionAction = new Container('action');
		$sessionModule->lastModule = $module;
		$sessionController->lastController = $controller;
		$sessionAction->lastAction = $action;
		
		$sessionUser = new Container('user');
		if(!$sessionUser->tendangnhap){
			return $this->redirect()->toRoute('auth');
		}
		else if($sessionUser->tendangnhap && $sessionUser->quyen != 1){
			return $this->redirect()->toRoute('Home');
		}
	}
    public function indexAction() {
		
		$this->kiemtra();
		
        $select = new Select();

        $order_by = $this->params()->fromRoute('order_by') ?
                $this->params()->fromRoute('order_by') : 'id';
        $order = $this->params()->fromRoute('order') ?
                $this->params()->fromRoute('order') : Select::ORDER_DESCENDING;
        $page = $this->params()->fromRoute('page') ? (int) $this->params()->fromRoute('page') : 1;

        $users = $this->getUserTable()->fetchAll($select->order($order_by . ' ' . $order));
        $itemsPerPage = 10;

        $users->current();
        $paginator = new Paginator(new paginatorIterator($users));
        $paginator->setCurrentPageNumber($page)
                ->setItemCountPerPage($itemsPerPage)
                ->setPageRange(7);

        return new ViewModel(array(
                    'order_by' => $order_by,
                    'order' => $order,
                    'page' => $page,
                    'paginator' => $paginator,
                ));
    }

    public function addAction() {
		
		$this->kiemtra();
		
		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new UserForm($dbAdapter);
        $form->get('submit')->setAttribute('value', 'Thêm');
		$viewModel = new ViewModel();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $user = new User();
            $form->setInputFilter($user->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $user->exchangeArray($form->getData());
				if($this->getUserTable()->check_exists($_POST['username'],0)){
					$viewModel->setVariable('error', 'Tên đăng nhập đã tồn tại');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_email($_POST['email'],0)){
					$viewModel->setVariable('error', 'Email đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else{
					$this->getUserTable()->saveUser($user);
	
					// Redirect to list of users
					return $this->redirect()->toRoute('user');
				}
            }
        }

        return array('form' => $form);
    }

    public function editAction() {
		$this->kiemtra();
		
        $id = (int) $this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('user', array('action' => 'add'));
        }
		$viewModel = new ViewModel();
        $user = $this->getUserTable()->getUser($id);
		if (!$user) {
            return $this->redirect()->toRoute('user');
        }

		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new UserForm($dbAdapter);
        $form->bind($user);
        $form->get('submit')->setAttribute('value', 'Sửa');
		$form->get('password')->setAttribute('type', 'hidden');
		$form->get('password')->setLabel('');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
				if($this->getUserTable()->check_exists($_POST['username'],$id)){
					$viewModel->setVariable('error', 'Tên đăng nhập đã tồn tại');
					$viewModel->setVariable('id', $id);
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_email($_POST['email'],$id)){
					$viewModel->setVariable('error', 'Email đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else{
                	$this->getUserTable()->saveUser($user);

					// Redirect to list of users
					return $this->redirect()->toRoute('user');
				}
            }
        }

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

    public function deleteAction() {
		$this->kiemtra();
		
        $id = (int) $this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('user');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost()->get('del', 'No');
            if ($del == 'Yes') {
                $id = (int) $request->getPost()->get('id');
                $this->getUserTable()->deleteUser($id);
            }

            // Redirect to list of users
            return $this->redirect()->toRoute('user');
        }

        return array(
            'id' => $id,
            'user' => $this->getUserTable()->getUser($id)
        );
    }

    public function getUserTable() {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('Admin\Model\UserTable');
        }
        return $this->userTable;
    }

}
